package user

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"git.myscrm.cn/golang/stark/v4"
	"gorm.io/gorm"
	"time"
)

type loginRepository struct {
	tenant_db.TenantDB
}

func NewLoginRepository() LoginRepositoryIface {
	return &loginRepository{}
}

func (l *loginRepository) SaveUserLogin(ctx context.Context, model *GfyxUserLoginPo) (int64, error) {
	result := l.GetTenantDB(ctx).Table(GfyxUserLoginPo{}.TableName()).Save(model)
	if result.Error != nil {
		stark.Logger.Errorf(ctx, "SaveUserBehavior save data : %+v, error: %+v", model, result.Error)
		return 0, result.Error
	}
	return model.ID, nil
}

// GetLoginInfoByToken 获取登录 token
func (l *loginRepository) GetLoginInfoByToken(ctx context.Context, token string) (*GfyxUserLoginPo, error) {
	loginInfo := &GfyxUserLoginPo{}
	db := l.GetTenantDB(ctx)
	err := db.Table(GfyxUserLoginPo{}.TableName()).
		Where("is_deleted", constants.IsDeletedFalse).
		Where("token = ?", token).
		Where("is_online = ?", 1).
		Where("expired_time >= ?", time.Now().Format("2006-01-02 15:04:05")).
		Find(loginInfo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		stark.Logger.Errorf(ctx, "repository-method:GetLoginInfoByToken, err:%v", err)
		return nil, err
	}
	return loginInfo, nil
}

// GetLoginInfo 获取登录信息
func (l *loginRepository) GetLoginInfo(ctx context.Context, condition map[string]interface{}) (*GfyxUserLoginPo, error) {
	loginInfo := &GfyxUserLoginPo{}
	db := l.GetTenantDB(ctx)
	err := db.Table(GfyxUserLoginPo{}.TableName()).
		Where("is_deleted", constants.IsDeletedFalse).
		Where(condition).
		Find(loginInfo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		stark.Logger.Errorf(ctx, "repository-method:GetLoginInfoByToken, err:%v", err)
		return nil, err
	}
	return loginInfo, nil
}
